package com.coolrui.converter;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.coolrui.common.utils.MockDataUtils;
import com.coolrui.domain.order.entity.OrderGoods;
import com.coolrui.domain.order.entity.UserOrder;
import com.coolrui.model.UserOrderVO;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.mapstruct.Mapper;
import org.mapstruct.Mapping;
import org.mapstruct.Named;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * User实体属性转换
 */
@Mapper(componentModel = "spring") // 让 MapStruct 生成的实现类成为 Spring Bean
public abstract class OrderConverter {
    @Autowired
    private MockDataUtils mockDataUtils;

    /**
     * 将 UserOrder 实体转换为 UserOrderVO
     */
    @Mapping(target = "orderGoods", source = "orderGoods", qualifiedByName = "orderGoodsToString")
    @Mapping(target = "userCityName", source = "userCity", qualifiedByName = "cityIdToCityName")
    @Mapping(target = "createTime", source = "createTime", qualifiedByName = "dateToString")
    @Mapping(target = "updateTime", source = "updateTime", qualifiedByName = "dateToString")
    public abstract UserOrderVO toUserOrderVO(UserOrder userOrder);

    public abstract List<UserOrderVO> toUserOrderVO(List<UserOrder> orderList);
    //=========================================自定义转换方法=====================================
    @Named("orderGoodsToString")
    public String orderGoodsToString(String orderGoods){
        if (StrUtil.isBlank(orderGoods)) {
            return "";
        }
        List<OrderGoods> goodsList = JSONUtil.toList(orderGoods, OrderGoods.class);
        if (CollUtil.isEmpty(goodsList)) {
            return "";
        }
        //4件商品:格力热水器*2，电风扇*2
        List<String> descList = new ArrayList<>();
        int totalNum = 0;
        for (OrderGoods goods : goodsList) {
            descList.add(String.format("%s*%s", goods.getGoodsName(), goods.getGoodsNum()));
            totalNum += goods.getGoodsNum();
        }
        return String.format("%s件商品:%s", totalNum, CollUtil.join(descList, "，"));
    }

    /**
     * 自定义方法：将 cityId 转为 cityName
     */
    @Named("cityIdToCityName")
    public String cityIdToCityName(Integer userCity) {
        return mockDataUtils.getCityName(userCity);
    }

    /**
     * 自定义方法：将 Date 转为格式化字符串
     */
    @Named("dateToString")
    public String dateToString(Date date) {
        if (date == null) return null;
        String format = "yyyy-MM-dd HH:mm:ss";
        return DateFormatUtils.format(date, format);
    }
}
